import editForm from "../form.vue";
import { handleTree } from "@/utils/tree";
import { message } from "@/utils/message";
import { getMenuList, getRoleList } from "@/api/system";
import { getUserInfoList, getAllcompany, saveOrEditUserInfo, getApplicationNameList, getExecptRoleInfo } from "@/api/empower";
import { ElMessage } from "element-plus";
import { transformI18n } from "@/plugins/i18n";
import { addDialog } from "@/components/ReDialog";
import { reactive, ref, onMounted, toRaw } from "vue";
import type { FormItemProps } from "../utils/types";
import type { PaginationProps } from "@pureadmin/table";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";
import { cloneDeep, isAllEmpty, deviceDetection } from "@pureadmin/utils";
import { useRoute, useRouter } from "vue-router";
export function useMenu() {
  const route = useRoute();
  const router = useRouter();
  let formVisible = ref(false)
  let eidtformRef = ref(null)
  let editform = ref({
    productFlag: '',//产品除外1是，0否
    companyFlag: '',//机构除外1是，0否
    permitCompanyCode: '11000000,13000000',
    permitCompanyName: '北京分公司,河北分公司',
    permitProductCode: '01,02',
    permitProductName: "水险,财险",
    userId: '',
    deptId: '',
    userCode: '',
    username: '',
    nickName: '',
    gender: '',
    phone: '',
    email: '',
    avatarName: '',
    avatarPath: '',
    password: '',
    comCode: '',
    comName: '',
    gradeId: '',
    gradeName: '',
    customerFlag: '',
    entryTime: '',
    resignTime: '',
    isAdmin: '',
    enabled: '',
    createBy: '',
    updateBy: '',
    pwdResetTime: '',
    createTime: '',
    updateTime: '',
    validStatus: '',
    roleInfo: [],
    systemCode: '',
    systemName: '',
    roleId: '',
    roleName: '',
  })
  let roleOptions = ref([])
  let roleOptions2 = ref([])
  let roleOptions3 = ref([])
  let roleOptions4 = ref([])
  let roleOptions5 = ref([])
  const formRef = ref();
  const dataList = ref([]);
  let loading3 = ref(true);
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true,
  });
  let selectPag = reactive({
    pageSize: 10,
    pageNum: 1,
    total: 0,
    userCode: "",//员工
    userName: "admin",
    comCode: "",//机构
    gradeId: "",//岗位
    // validStatus: '', //状态
    // startDate: "",
    // endDate: "",
    // value1: ''
  })
  const getMenuType = (type, text = false) => {
    switch (type) {
      case 0:
        return text ? "菜单" : "primary";
      case 1:
        return text ? "iframe" : "warning";
      case 2:
        return text ? "外链" : "danger";
      case 3:
        return text ? "按钮" : "info";
    }
  };

  const columns: TableColumnList = [
    {
      label: "员工姓名",
      prop: "username",
    },
    {
      label: "岗位",
      prop: "gradeName",
    },
    {
      label: "归属机构",
      prop: "comName"
    },
    {
      label: "联系方式",
      prop: "phone"
    },
    {
      label: "邮箱",
      prop: "email"
    },
    {
      label: "客户标识",
      prop: "customerFlag"
    },
    {
      label: "状态",
      prop: "enabled",
      slot: "enabled"
    },
    {
      label: "入职时间",
      prop: "entryTime"
    },
    {
      label: "操作",
      fixed: "right",
      width: 210,
      slot: "operation"
    }
  ];
  function onChange() {

  }
  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }
  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
    selectPag.pageSize = val;
    selectPag.pageNum = 1
    onSearch();
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
    selectPag.pageNum = val
    onSearch();
  }

  function resetForm(formEl) {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  }
  async function onSearch() {
    loading3.value = true;
    const { data } = await getUserInfoList(selectPag);
    dataList.value = data.taskInfoVos.list;
    selectPag.total = data.taskInfoVos.totalSize;

    setTimeout(() => {
      loading3.value = false;
    }, 500);
  }

  function openDialog(row) {
    console.log(row);
    editform.value = { ...row }
    console.log(editform.value);
    getgetExecptRoleInfo(row.userId)
    editform.value.roleId = ''
    editform.value.roleName = ''
    formVisible.value = true
  }
  const closeDialog = () => {
    formVisible.value = false
  }
  async function handleDelete(id) {
    const res = await getUserInfoList({ userId: id });
    if (res.code == 200) {
      ElMessage({
        message: res.msg,
        type: 'success'
      })
      selectPag.pageNum = 1
      onSearch();
    } else {
      ElMessage({
        message: res.msg,
        type: 'error'
      })
    }
  }
  //保存
  const saveHandle = async () => {
    let res = await saveOrEditUserInfo(editform.value)
    if (res.code == 200) {
      ElMessage({
        message: res.msg,
        type: 'success'
      })
      formVisible.value = false
      selectPag.pageNum = 1
      onSearch();
    } else {
      ElMessage({
        message: res.msg,
        type: 'error'
      })
    }
  }
  //获取机构
  const getgetAllcompany = async () => {
    let res = await getAllcompany()
    if (res.code == 200) {
      roleOptions.value = res.data
    } else {
      roleOptions.value = []
    }
  }
  //获取应用系统
  const getgetApplicationNameList = async () => {
    let res = await getApplicationNameList();
    if (res.code == 200) {
      roleOptions4.value = res.data;
    }
  };
  //获取角色
  const getgetExecptRoleInfo = async (id) => {
    let res = await getExecptRoleInfo({ userId: id.toString() })
    if (res.code == 200) {
      roleOptions5.value = res.data;
    }
  }
  //应用
  const changesystem = () => {
    let i = roleOptions4.value.findIndex(
      item => item.applicationCode == editform.value.systemCode
    );
    if (i != -1) {
      editform.value.systemName = roleOptions4.value[i].applicationName;
    }
  }
  //角色
  const changeRole = () => {
    let i = roleOptions5.value.findIndex(
      item => item.roleId == editform.value.roleId
    );
    if (i != -1) {
      editform.value.roleName = roleOptions5.value[i].name;
    }
  }
  onMounted(() => {
    getgetApplicationNameList()
    getgetAllcompany()
    onSearch();
  });

  return {
    changeRole,
    changesystem,
    saveHandle,
    selectPag,
    pagination,
    eidtformRef,
    editform,
    closeDialog,
    formVisible,
    roleOptions,
    roleOptions2,
    roleOptions3,
    roleOptions4,
    roleOptions5,
    loading3,
    columns,
    dataList,
    onChange,
    /** 搜索 */
    onSearch,
    /** 重置 */
    resetForm,
    /** 新增、修改菜单 */
    openDialog,
    /** 删除菜单 */
    handleDelete,
    handleSelectionChange,
    handleSizeChange,
    handleCurrentChange,
  };
}
